<?php

namespace common\models\user;

use Yii;
use yii\db\Exception;
use common\helpers\IpHelper;

/**
 * 用户积分账户信息
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class UserAccount extends \common\models\sghome\UserAccount {

    const USEAGE_SHOP_CONSUME = 'shop_consume';
    const USEAGE_SHOP_REFUND = 'shop_refund';
    const USEAGE_SHOP_ROLLBACK = 'shop_rollback';

    /**
     * 获取用户积分账户余额
     * @return integer
     */
    public function getPoints() {
        return $this->available_credit;
    }

    /**
     * 获取用户积分账户余额
     * @return integer
     */
    public function getCredit() {
        return $this->available_credit;
    }

    /**
     * 设置积分
     * @param integer $points 积分值
     * @param string $usage 使用类型
     */
    public function setPoints($points, $usage = self::USEAGE_SHOP_CONSUME) {
        if ($usage === static::USEAGE_SHOP_CONSUME) {
            //可用积分
            $this->available_credit -= $points;
            //消费积分
            $this->spend_credit += $points;
        } elseif ($usage === static::USEAGE_SHOP_REFUND) {
            //可用积分
            $this->available_credit += $points;
            //消费积分
            $this->spend_credit -= $points;
        }
    }

    /**
     * 记录账户积分变动日志
     * @param integer $value 积分值
     * @param string $from 来源
     * @param integer $fromId 来源ID
     * @param string $mark 备注内容
     * @throws Exception
     */
    public function recordLog($type, $value, $from, $fromId, $mark) {
        $log = new UserAccountLog($this->user_id);
        $log->change_type = $type;
        if ($type == UserAccountLog::CHANGE_TYPE_SHOP_CONSUME) {
            $value = intval(abs($value) * -1);
        } elseif ($type == UserAccountLog::CHANGE_TYPE_SHOP_REFUND) {
            $value = intval(abs($value));
        } else {
            throw new Exception('非法使用范围！');
        }
        $log->setAttributes([
            'user_id' => $this->user_id,
            'change_credit' => $value,
            'current_credit' => $this->getPoints(),
            'ip' => IpHelper::getRealIp(true),
            'remark' => $mark,
            'relation_table' => $from,
            'relation_table_id' => $fromId,
            'is_rollback' => 1,
        ]);
        Yii::error($log->attributes);
        Yii::error($log::$sequenceField);
        if (!$log->save()) {
            Yii::error($log->attributes);
            throw new Exception('积分日志更新失败！');
        }

        return $log;
    }

    /**
     * 根据UID查询账户信息
     * @param integer $uid
     * @return static|null
     */
    public static function findByUserId($uid) {
        return static::find()->andWhere([
            'user_id' => $uid
        ])->one();
    }

}
